package cn.cloudreal.cbms.system.action;

import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import cn.cloudreal.cbms.common.util.Constants;
import cn.cloudreal.cbms.common.util.PageBean;
import cn.cloudreal.cbms.system.service.PurviewService;
import cn.cloudreal.cbms.vo.Purview;

import com.opensymphony.xwork2.ActionSupport;

/**
 * <p>
 * Title: CBMS
 * </p>
 * <p>
 * Description:权限管理查询数据服务层视图类
 * </p>
 * <p>
 * Copyright: Copyright (c) 2012
 * </p>
 * <p>
 * Company:云恒瑞通
 * </p>
 * 
 * @author Gaoxuejiao
 * @date 2012-07-17
 */
public class PurviewAction extends ActionSupport
{
    /** serialVersionUID */
    private static final long serialVersionUID = 1L;

    /** 日志工具类实例 */
    private static final Logger log = Logger.getLogger(PurviewAction.class);

    /**
     * 注入service 类
     */
    private PurviewService purviewService;

    /** id */
    long id;

    /** 当前页 */
    int currentPage;

    /** 组织架构列表 */
    private List<Purview> purviewLists;

    /**
     * 用户实体信息
     */
    private Purview purview;

    /** 分页对象 */
    PageBean page;

    /** falg：1：查看，2：修改初始化，3：修改确认 ，4：新增保存 */
    String flag;

    /**
     * 列表
     * 
     * @return String
     */
    public String getPurviewList()
    {
        // 打印进入方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Enter PurviewAction list() method,return String");
        }
        try
        {
            purviewLists = new ArrayList<Purview>();
            // 获取集合
            purviewLists = purviewService.getAllPurviews(new Purview());

            StringBuffer ss = new StringBuffer("[");
            for (int i = 0; i < purviewLists.size(); i++)
            {
                if (i == 0)
                {
                    // 获取第一个 节点权限详情
                    purview = purviewLists.get(i);
                }
                // 获取集合单独对象
                Purview pur = new Purview();
                pur = purviewLists.get(i);

                // 如果当前是父节点打开
                if (pur.getParentId().intValue() == -1)
                {
                    ss.append("{ id:'" + pur.getId() + "',  pId:"
                            + pur.getParentId() + ",   name:'"
                            + pur.getActionName() + "',open:true},");
                }
                else
                {
                    ss.append("{ id:'" + pur.getId() + "',  pId:"
                            + pur.getParentId() + ",   name:'"
                            + pur.getActionName() + "'},");
                }
            }
            if (null != purviewLists && purviewLists.size() > 0)
            {
                // 获取第一个节点详情
                flag = ss.substring(0, ss.toString().length() - 1).toString();

            }
            else
            {
                flag = ss.toString();
            }
            flag += "];";
        }
        catch (Exception e)
        {
            // TODO: handle exception 添加异常信息 返回error
            log.error("Error PurviewAction list() method,return String", e);
            return ERROR;
        }

        // 打印退出方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Exit PurviewAction list() method,return String");
        }
        return SUCCESS;
    }

    /**
     * 查看
     * 
     * @return
     */
    public String purviewDetail()
    {
        // 打印进入方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Enter PurviewAction view() method,return String");
        }
        // response 对象
        HttpServletResponse response = ServletActionContext.getResponse();
        PrintWriter out = null;
        try
        {
            // 获取PrintWriter对象
            ServletActionContext.getRequest()
                    .setCharacterEncoding(Constants.STR_UTF);
            response.setContentType(Constants.STR_CHARSET);
            out = response.getWriter();

            // 如果不为空 执行查询
            if (null != purview && null != purview.getId())
            {
                purview = purviewService.getPurview(purview.getId());

                Map map = new HashMap<Object, Object>();
                map.put("purview", purview);

                JSONArray jo = JSONArray.fromObject(map);

                out.print(jo.toString());
                out.flush();
                out.close();
                return null;
            }
        }
        catch (Exception e)
        {
            // TODO: handle exception 添加异常日志
            log.error("Error PurviewAction view() method,return String edit", e);
            // return ERROR;
            Map map = new HashMap<Object, Object>();
            map.put("msg", "error");

            JSONArray jo = JSONArray.fromObject(map);

            out.print(jo.toString());
            out.flush();
            out.close();
            return null;
        }
        return null;
    }

    /**
     * 跳转到修改页面
     * 
     * @return SUCCESS
     */
    public String doPurviewEdit()
    {
        // 打印进入方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Enter PurviewAction view() method,return String");
        }
        // response 对象
        HttpServletResponse response = ServletActionContext.getResponse();
        PrintWriter out = null;
        try
        {
            // 获取PrintWriter对象
            ServletActionContext.getRequest()
                    .setCharacterEncoding(Constants.STR_UTF);
            response.setContentType(Constants.STR_CHARSET);
            out = response.getWriter();

            if (null != purview)
            {
                purviewService.updatePurview(purview);
                out.print("true");
                out.flush();
                out.close();
                return null;
            }
        }
        catch (Exception e)
        {
            // TODO: handle exception 添加异常日志
            log.error("Error PurviewAction view() method,return String edit", e);
            // return ERROR;
            out.print("error");
            out.flush();
            out.close();
            return null;
        }
        return null;
    }

    /**
     * 删除
     * 
     * @return SUCCESS
     */
    public String deletePurview()
    {
        // 打印进入方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Enter PurviewAction delete() method,return String");
        }

        // response 对象
        HttpServletResponse response = ServletActionContext.getResponse();
        PrintWriter out = null;
        try
        {
            // 获取PrintWriter对象
            ServletActionContext.getRequest()
                    .setCharacterEncoding(Constants.STR_UTF);
            response.setContentType(Constants.STR_CHARSET);
            out = response.getWriter();
            // 如果不为空 执行查询
            if (null != purview && null != purview.getId())
            {
                // 验证当前权限节点是否正在使用
                if (purviewService.isUsePurview(purview.getId()))
                {
                    out.print("false");
                    out.flush();
                    out.close();
                    return null;
                }
                else
                {
                    purviewService.delPurview(purview);
                    out.print("true");
                    out.flush();
                    out.close();

                    return null;
                }

            }
        }
        catch (Exception e)
        {
            // TODO: handle exception 添加异常日志 返回Error
            log.error("Error PurviewAction delete() method,return String", e);
            // return ERROR;
            out.print("error");
            out.flush();
            out.close();
            return null;
        }

        // 打印退出方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Exit PurviewAction delete() method,return String ");
        }
        return null;
    }

    /**
     * 保存
     * 
     * @return SUCCESS
     */
    public String doAddPurview()
    {
        // 打印进入方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Enter PurviewAction save() method,return String");
        }

        // response 对象
        HttpServletResponse response = ServletActionContext.getResponse();
        PrintWriter out = null;
        try
        {
            // 获取PrintWriter对象
            ServletActionContext.getRequest()
                    .setCharacterEncoding(Constants.STR_UTF);
            response.setContentType(Constants.STR_CHARSET);
            out = response.getWriter();

            // 非空判断
            if (null != purview && null != purview.getPrivCode())
            {
                String temp = purview.getPrivCode().trim();
                purview.setPrivCode(temp.substring(0, temp.length() - 1));
                int result = purviewService.addPurview(purview);
                out.print(result);
                out.flush();
                out.close();
                return null;
            }
        }
        catch (Exception e)
        {
            // TODO: handle exception
            // 打印方法体异常日志
            log.error("Error PurviewAction  doAddPurview() method,return String ",
                    e);
            // return ERROR;
            out.print("error");
            out.flush();
            out.close();
            return null;
        }

        // 打印退出方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Exit PurviewAction  doAddPurview() method,return String ");
        }
        return null;
    }

    /**
     * 验证当前 编号是否已经存在
     * 
     * @return SUCCESS
     */
    public String isExistUsePurCode()
    {
        // 打印进入方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Enter PurviewAction isExistUsePurCode() method,return String");
        }

        // response 对象
        HttpServletResponse response = ServletActionContext.getResponse();
        PrintWriter out = null;
        try
        {
            // 获取PrintWriter对象
            ServletActionContext.getRequest()
                    .setCharacterEncoding(Constants.STR_UTF);
            response.setContentType(Constants.STR_CHARSET);
            out = response.getWriter();

            // 非空判断
            if (null != purview && null != purview.getPrivCode())
            {
                List<Purview> lists = purviewService.getAllPurviews(purview);
                if (null != lists && lists.size() > 0)
                {
                    out.print("true");
                    out.flush();
                    out.close();
                    return null;
                }
            }
        }
        catch (Exception e)
        {
            // TODO: handle exception
            // 打印方法体异常日志
            log.error("Error PurviewAction  isExistUsePurCode() method,return String ",
                    e);
            // return ERROR;
            out.print("error");
            out.flush();
            out.close();
        }

        // 打印退出方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Exit PurviewAction  isExistUsePurCode() method,return String ");
        }
        return null;
    }

    /**
     * 验证当前 名称是否已经存在
     * 
     * @return SUCCESS
     */
    public String isExistUsePurName()
    {
        // 打印进入方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Enter PurviewAction isExistUsePurName() method,return String");
        }

        // response 对象
        HttpServletResponse response = ServletActionContext.getResponse();
        PrintWriter out = null;
        try
        {
            // 获取PrintWriter对象
            ServletActionContext.getRequest()
                    .setCharacterEncoding(Constants.STR_UTF);
            response.setContentType(Constants.STR_CHARSET);
            out = response.getWriter();

            // 非空判断
            if (null != purview && null != purview.getActionName())
            {
                String code = URLDecoder.decode(purview.getActionName(),
                        "UTF-8");
                purview.setActionName(code);

                List<Purview> lists = purviewService.getAllPurviews(purview);
                if (null != lists && lists.size() > 0)
                {
                    out.print("true");
                    out.flush();
                    out.close();
                    return null;
                }
            }
        }
        catch (Exception e)
        {
            // TODO: handle exception
            // 打印方法体异常日志
            log.error("Error PurviewAction  isExistUsePurName() method,return String ",
                    e);
            out.print("error");
            out.flush();
            out.close();
            // return ERROR;
        }

        // 打印退出方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Exit PurviewAction  isExistUsePurName() method,return String ");
        }
        return null;
    }

    public int getCurrentPage()
    {
        return currentPage;
    }

    public void setCurrentPage(int currentPage)
    {
        this.currentPage = currentPage;
    }

    public long getId()
    {
        return id;
    }

    public void setId(long id)
    {
        this.id = id;
    }

    public String getFlag()
    {
        return flag;
    }

    public void setFlag(String flag)
    {
        this.flag = flag;
    }

    public PageBean getPage()
    {
        return page;
    }

    public void setPage(PageBean page)
    {
        this.page = page;
    }

    public List<Purview> getPurviewLists()
    {
        return purviewLists;
    }

    public void setPurviewLists(List<Purview> purviewLists)
    {
        this.purviewLists = purviewLists;
    }

    public Purview getPurview()
    {
        return purview;
    }

    public void setPurview(Purview purview)
    {
        this.purview = purview;
    }

    public PurviewService getPurviewService()
    {
        return purviewService;
    }

    public void setPurviewService(PurviewService purviewService)
    {
        this.purviewService = purviewService;
    }

}
